import axios from 'axios';

import setting, {
  defaultRequestInterceptors,
  defaultResponseInterceptors,
} from './setting';
import {
  AxiosInstance,
  AxiosResponse,
  InternalAxiosRequestConfig,
} from './types';

const abortControllerMap: Map<string, AbortController> = new Map();

// 创建Axios实例，参数为自定义的Axios相关配置
const axiosInstance: AxiosInstance = axios.create({
  ...setting,
});

// Axios实例添加请求拦截器，缓存请求，用于取消请求
axiosInstance.interceptors.request.use((req: InternalAxiosRequestConfig) => {
  const controller = new AbortController();
  req.signal = controller.signal;
  const url = req.url || '';
  abortControllerMap.set(url, controller);
  return req;
});

// Axios实例添加请求拦截器，处理请求参数
axiosInstance.interceptors.request.use(defaultRequestInterceptors);

// Axios实例添加响应拦截器，删除缓存的请求
axiosInstance.interceptors.response.use(
  (res: AxiosResponse) => {
    const url = res.config.url || '';
    abortControllerMap.delete(url);
    return res.data;
  },
  (err: any) => err
);

// Axios实例添加响应拦截器，处理响应数据
axiosInstance.interceptors.response.use((response: any) => {
  return defaultResponseInterceptors(response);
});

const service = {
  request: (config: InternalAxiosRequestConfig) => {
    return new Promise((resolve, reject) => {
      axiosInstance
        .request(config)
        .then((res) => {
          resolve(res);
        })
        .catch((err: any) => {
          reject(err);
        });
    });
  },
  cancelRequest: (url: string | string[]) => {
    const urlList = Array.isArray(url) ? url : [url];
    urlList.forEach((_url) => {
      abortControllerMap.get(_url)?.abort();
      abortControllerMap.delete(_url);
    });
  },
  cancelAllRequest() {
    abortControllerMap.forEach((controller) => {
      controller.abort();
    });
    abortControllerMap.clear();
  },
};

export default service;
